<template>
  <a-card :bordered="false">

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="8" :sm="8">
            <a-form-item label="订单编号">
              <a-input placeholder="请输入订单编号" v-model="queryParam.id"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-item label="收货人号码">
              <a-input placeholder="请输入收货人号码" v-model="queryParam.receiverPhone"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-item label="订单状态">
              <j-multi-select-tag v-model="status_MultiString" placeholder="请选择订单状态" dictCode="order_status"/>
              <!--<j-dict-select-tag v-model="queryParam.status" placeholder="请选择订单状态" dictCode="order_status"/>-->
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-item label="审核状态">
              <a-select placeholder="请选择审核状态" v-model="queryParam.productStatus_MultiString">
                <a-select-option value="">请选择</a-select-option>
                <a-select-option value="1">未审核</a-select-option>
                <a-select-option value="2,3,4,5,6,7">已审核</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :md="8" :sm="8">
            <a-form-item label="下单时间">
              <a-range-picker format="YYYY-MM-DD HH:mm:ss"
                              style="width:325px;"
                              :show-time="{
                                hideDisabledOptions: true,
                                defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
                              }"
                              :placeholder="['开始时间', '结束时间']"
                              @change="onCreateTimeChange"/>
            </a-form-item>
          </a-col>


          <template v-if="toggleSearchStatus">
            <a-col :md="8" :sm="8">
              <a-form-item label="实付金额">
                <a-input placeholder="最小金额" type="ge" v-model="queryParam.payAmount_begin"
                         style="width:calc(50% - 15px);"></a-input>
                <span class="group-query-strig"> ~ </span>
                <a-input placeholder="最大金额" type="le" v-model="queryParam.payAmount_end"
                         style="width:calc(50% - 15px);"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-item label="支付方式">
                <j-multi-select-tag v-model="queryParam.payType_MultiString" placeholder="请选择支付方式"
                                    dictCode="order_pay_type"/>
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="8" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>

        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button icon="download" @click="handleExportXls('团购订单管理')">导出</a-button>
<!--      <a-button type="danger" v-has="'oms:exportByFinance'" icon="download" @click="handleExportXlsForFinance('订单管理')">
        财务导出
      </a-button>-->
      <a-button @click="handleConfirm" type="primary" v-has="'oms:confirmByOperate'" icon="file-done">团购订单审核</a-button>
      <span>订单状态为【已确认】且货品状态为【锁定】的订单，即为待审核的订单</span>
      <!--<a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>
      <a-button @click="handleAdd" type="primary" icon="check-square">订单确认</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>-->
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i>
        <span>已选择</span>
        <a style="font-weight: 600">
          {{ selectedRowKeys.length }}
        </a>
        <span>项</span>
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :scroll="{ x: 1900 }"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">

        <span slot="action" slot-scope="text, record">
          <a @click="handleShowDetail(record)">查看</a>
          <a-divider type="vertical"/>
          <a @click="handleTrace(record)">轨迹</a>
        </span>


        <table slot="orderItemName" slot-scope="text, record" class="orderItemTable">
          <tr v-for="(item, index) in record.omsOrderItemList" :key="item.id">
            <td>{{ item.productName }}</td>
          </tr>
        </table>
        <table slot="orderItemPrice" slot-scope="text, record" class="orderItemTable">
          <tr v-for="(item, index) in record.omsOrderItemList" :key="item.id">
            <td>{{ item.productPrice }}</td>
          </tr>
        </table>
        <table slot="orderItemQuantity" slot-scope="text, record" class="orderItemTable">
          <tr v-for="(item, index) in record.omsOrderItemList" :key="item.id">
            <td>{{ item.productQuantity }}</td>
          </tr>
        </table>

        <!--<a-list size="small" :data-source="record.omsOrderItemList">
          <a-list-item slot="renderItem" class="ant-input-span" slot-scope="item, index">
            {{ itemToString(item)  }}
          </a-list-item>
        </a-list>-->

      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->

    <oms-order-view-modal ref="OmsOrderViewModal" @ok="modalFormOk"/>

    <oms-order-trace-modal ref="OmsOrderTraceModal" @ok="modalFormOk"/>


  </a-card>
</template>

<script>

import { httpAction, getAction, postAction, downFile } from '@/api/manage'
import moment from 'moment'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import OmsOrderViewModal from './modules/OmsOrderViewModal'
import OmsOrderTraceModal from './modules/OmsOrderTraceModal'
import JMultiSelectTag from '../../components/dict/JMultiSelectTag'

export default {
  name: 'OmsGroupBuyOrderList',
  mixins: [JeecgListMixin],
  components: {
    JMultiSelectTag,
    OmsOrderViewModal,
    OmsOrderTraceModal
  },
  data() {
    return {
      description: '团购订单管理页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 50,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '门店',
          width: 120,
          align: 'center',
          dataIndex: 'storeId_dictText'
        },
        {
          title: '订单编号',
          width: 160,
          align: 'center',
          dataIndex: 'orderSn'
        },
        {
          title: '订单类型',
          width: 90,
          align: 'center',
          dataIndex: 'orderType_dictText'
        },
        {
          title: '商品明细',
          align: 'center',
          children: [
            {
              title: '商品名称',
              width: 180,
              align: 'center',
              scopedSlots: { customRender: 'orderItemName' },
              customCell: (record) => {
                return {
                  'style': {
                    padding: 0,
                    margin: 0
                  }
                }
              }
            },
            {
              title: '单价',
              width: 80,
              align: 'center',
              scopedSlots: { customRender: 'orderItemPrice' },
              customCell: (record) => {
                return {
                  'style': {
                    padding: 0,
                    margin: 0
                  }
                }
              }
            },
            {
              title: '数量',
              width: 80,
              align: 'center',
              scopedSlots: { customRender: 'orderItemQuantity' },
              customCell: (record) => {
                return {
                  'style': {
                    padding: 0,
                    margin: 0
                  }
                }
              }
            }]
        },
        {
          title: '订单状态',
          width: 90,
          align: 'center',
          dataIndex: 'status_dictText'
        },
        {
          title: '货品状态',
          width: 90,
          align: 'center',
          dataIndex: 'productStatus_dictText'
        },
        {
          title: '支付状态',
          width: 90,
          align: 'center',
          dataIndex: 'payStatus_dictText'
        },
        {
          title: '下单时间',
          width: 130,
          align: 'center',
          dataIndex: 'createTime'
        },
        {
          title: '支付时间',
          width: 130,
          align: 'center',
          dataIndex: 'paymentTime'
        },
        {
          title: '发货时间',
          width: 100,
          align: 'center',
          dataIndex: 'deliveryTime'
        },
        {
          title: '支付方式',
          width: 80,
          align: 'center',
          dataIndex: 'payType_dictText'
        },
        {
          title: '商品总金额',
          width: 100,
          align: 'center',
          dataIndex: 'totalAmount'
        },
        {
          title: '实付金额',
          width: 90,
          align: 'center',
          dataIndex: 'payAmount'
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 160,
          align: 'center',
          fixed: 'right',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 请求参数
      url: {
        list: '/oms/omsOrder/groupBuyList',
        exportXlsUrl: 'oms/omsOrder/exportXls',
        importExcelUrl: 'oms/omsOrder/importExcel',
        exportXlsForFinance: 'oms/omsOrder/exportXlsForFinance',
        groupBuyConfirmBatch: '/oms/omsOrder/groupBuyConfirmBatch'
      },
      status_MultiString: '1,2,3'
    }

  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  created() {
    this.queryParam.status_MultiString = '1,2,3'
  },
  watch: {
    status_MultiString(v) {
      this.queryParam.status_MultiString = this.status_MultiString
    }
  },
  methods: {
    moment,
    onStatusChange: function(value) {
      console.log(value)
      this.queryParam.status_MultiString = value
    },
    onCreateTimeChange: function(value, dateString) {
      console.log(dateString[0], dateString[1])
      this.queryParam.createTime_begin = dateString[0]
      this.queryParam.createTime_end = dateString[1]
    },
    handleShowDetail(record) {
      this.$refs.OmsOrderViewModal.show(record)
    },
    handleTrace(record) {
      this.$refs.OmsOrderTraceModal.show(record)
    },
    initDictConfig() {
    },
    itemToString(item) {
      return '货号：' + item.productSn + '  价格：' + item.productPrice + '  数量：' + item.productQuantity
    },
    handleExportXlsForFinance(fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      let param = { ...this.getQueryParams() }
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      console.log('导出参数', param)
      downFile(this.url.exportXlsForFinance, param).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    handleConfirm: function() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else {
        var ids = []
        var index = this.selectionRows.findIndex(item => {
          if (item.payStatus !== 4 || item.productStatus !== 1 || item.status !== 1) {
            return true
          }
        })
        if (index !== -1) {
          this.$message.warning('确认订单只允许选择已支付且已确认的订单！')
          return
        }
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids.push(this.selectedRowKeys[a])
        }
        var that = this
        this.$confirm({
          title: '确认订单',
          content: '是否确认选中的订单?',
          onOk: function() {
            that.loading = true
            postAction(that.url.groupBuyConfirmBatch, ids).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.loading = false
            })
          }
        })
      }
    }

  }
}
</script>
<style scoped>
.ant-input-span {
  white-space: pre;
  margin-left: -46px;
}

.orderItemTable {
  width: 100%;
  height: 100%;
  border: 1px;
}

.orderItemTable td {
  border-bottom: #e8e8e8 1px solid;
  text-align: center;
}

.orderItemTable tr:last-child td {
  border-bottom: #fff 1px solid;
}

@import '~@assets/less/common.less';
</style>